package com.mybatis.jpa.statement.builder;

import com.mybatis.jpa.meta.PersistentMeta;
import com.mybatis.jpa.statement.MybatisStatementAdapter;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.SqlCommandType;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 主要提供主键策略
 * @author wanglei
 * @date 2020 -02-06 11:06:32
 */
public abstract class BaseInsertBuilder implements StatementBuildable {
    /**
     * 设置主键策略
     * @param adapter
     * @param persistentMeta
     * @param method
     */
    public void setKeyGenerator(MybatisStatementAdapter adapter, PersistentMeta persistentMeta, Method method){
        // 返回值类型
        adapter.setResultType(int.class);
        adapter.setResultMapId(null);

        adapter.setSqlCommandType(SqlCommandType.INSERT);
        Field primaryField = persistentMeta.getPrimaryColumnMeta().getField();
        if(primaryField.getType() == Integer.class || primaryField.getType() == int.class)
        {
            // 主键策略
            adapter.setKeyGenerator(new Jdbc3KeyGenerator());
            adapter.setKeyProperty(primaryField.getName());
        }
        else
        {
            adapter.setKeyGenerator(new NoKeyGenerator());
            adapter.setKeyProperty(null);
        }
        adapter.setKeyColumn(null);
    }
}
